from flask import g, jsonify, render_template, redirect, request, session, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blue


# 个人中心主页显示
@profile_blue.route("/user_center")
@user_login_data
def user_center_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict()
    }
    return render_template("news/user.html", data=data)


# 个人中心基本资料网页
@profile_blue.route("/user_base_info", methods=["GET", "POST"])
@user_login_data
def user_base_info():
    """
    如果是get请求，将渲染的主页展示到框架中
    如果是post请求
    1、获取参数
    2、校验参数，数据是否存在
    3、向数据库中存储数据
    4、返回
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if request.method == "GET":
        return render_template("news/user_base_info.html", data={"user": user.to_dict()})
    else:
        # 获取参数
        params_dict = request.json
        nick_name = params_dict.get("nick_name")
        signature = params_dict.get("signature")
        gender = params_dict.get("gender")

        # 校验参数
        if not all([nick_name, gender, signature]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 数据库存储信息
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender

        # 更新session中保存的nick_name
        session["nick_name"] = nick_name

        return jsonify(errno=RET.OK, errmsg="保存成功")


# 用户头像上传
@profile_blue.route("/user_avatar", methods=["GET", "POST"])
@user_login_data
def user_avatar():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pic_info.html", data={"user": user.to_dict()})

    # 获取上传的文件
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR, errmsg="文件读取错误")

    # 将文件上传至七牛云
    try:
        avatar_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="文件上传失败")

    # 将头像url赋值给user
    user.avatar_url = avatar_url
    current_app.logger.info("头像存储url:%s" % avatar_url)

    return jsonify(errno=RET.OK, errmsg="上传成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_url})


# 密码修改
@profile_blue.route("/user_pwd_change", methods=["GET", "POST"])
@user_login_data
def user_pwd_change():
    user = g.user
    if request.method == "GET":
        return render_template("news/user_pass_info.html", data={"user": user.to_dict()})

    """
    1、接收参数old_password，new_password
    2、校验参数，原密码是否正确
    3、存入新密码
    4、返回
    """
    # 1、接收参数old_password，new_password
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2、校验参数，原密码是否正确
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 3、存入新密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="密码修改成功")


# 个人中心收藏新闻展示
@profile_blue.route("/collection")
@user_login_data
def user_news_collection():
    # 获取页码
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    user = g.user

    # 根据页码查询用户收藏数据分页查询
    paginate = None
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)

    collections = []
    current_page = 1
    total_page = 1
    if paginate:
        collection_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
        collections = [news.to_dict() for news in collection_list]
    data = {
        "collections": collections,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_collection.html", data=data)


# 发布新闻
@profile_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    if request.method == "GET":
        # 从数据库查询新闻分类，替换html中新闻分类
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        # 转化数据
        category_dict_list = [category.to_dict() for category in categories]

        if category_dict_list:
            category_dict_list.pop(0)
        data = {
            "categories": category_dict_list
        }
        return render_template("news/user_news_release.html", data=data)

    else:
        """
        1、form表单提交数据title，category_id，digest，index_image，content
        2、校验参数
        3、校验读取图片
        4、创建新闻对象
        5、向数据库存储数据
        6、返回
        """
        # 获取参数
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        source = "个人发布"

        # 校验参数
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 读取图片信息
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 上传至七牛云
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")

        # 创建新闻对象
        news = News()
        news.title = title
        news.digest = digest
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        news.category_id = category_id
        news.content = content
        news.source = source
        news.user_id = g.user.id
        news.status = 1

        # 将新闻提交至数据库
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据存储失败")
        # 返回操作结果
        return jsonify(errno=RET.OK, errmsg="新闻发布成功，等待审核中")


# 个人中心新闻列表审核
@profile_blue.route("/news_list")
@user_login_data
def news_list():
    """
    1、获取页码
    2、根据页码分页查询数据
    3、组合返回数据
    4、返回结果
    :return:
    """
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 分页查询数据
    user = g.user
    news_list = []
    page = 1
    pages = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 当前页数据
        news_list = paginate.items
        # 当前页数
        page = paginate.page
        # 总页数
        pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = [news.to_review_dict() for news in news_list]
    data = {
        "news_list": news_dict_list,
        "current_page": page,
        "total_page": pages
    }

    return render_template("news/user_news_list.html", data=data)


# 个人中心我的关注
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    # 分页查询登录用户已关注作者
    user = g.user
    p = request.args.get('p', 1)

    current_page = 1
    total_page = 1
    author_list = []
    try:
        paginate = user.followed.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        author_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 数据转化
    user_dict_list = [author.to_dict() for author in author_list]
    data = {
        'current_page': current_page,
        'total_page': total_page,
        'users': user_dict_list
    }

    return render_template('news/user_follow.html', data=data)


# 其他用户个人信息展示
@profile_blue.route('/other_info')
@user_login_data
def other_info():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 获取作者信息及分页信息
    author_id = request.args.get('user_id')
    p = request.args.get('p', 1)
    print(author_id)
    print(p)
    if not all([author_id, p]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 获取作者
    author = None
    try:
        author = user.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)

    if not author:
        abort(404)

    # 分页获取作者新闻列表
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = author.news_list.paginate(p, 1, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_li = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 转换数据
    news_dict_list = [news.to_dict() for news in news_li]

    # 判断用户是否注过该作者
    is_followed = False
    if user:
        if author.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    data = {
        "other_info": author.to_dict(),
        "user": user.to_dict(),
        "is_followed": is_followed,
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template('news/other.html', data=data)
